<?php

namespace app\trwl\controller;

use support\Request;

class SoundController
{
    
    //播放语音
    public function play(Request $request)
    {
        $device_name = $request->post('device_name','');
        if(!$device_name){
            return json(['code'=>0,'msg'=>'缺失参数device_name']);
        }
        $app_id = $request->post('app_id','');
        if(!$app_id){
            return json(['code'=>0,'msg'=>'缺失参数app_id']);
        }
        $password = $request->post('password','');
        if(!$password){
            return json(['code'=>0,'msg'=>'缺失参数password']);
        }
        $msg = $request->post('msg','');
        if(!$msg){
            return json(['code'=>0,'msg'=>'缺失参数msg']);
        }
        $ts = time();
        $sign = md5(md5($password).$ts);
        $url = 'https://iot-api.unisoft.cn/'.$app_id.'/device/control/?sign='.$sign.'&ts='.$ts;
        $data['device'] = $device_name;
        $data['order'] = [
            'play:gbk:16'=>$msg
        ];
        $res = $this->PostJson($url,$data);
        if($res['code']==200){
            return json(['code'=>1,'msg'=>'ok','data'=>[]]);
        }else{
            return json($res);
        }
    }
    //发送json请求函数
    public function PostJson($url, $data = NULL,$headers=[])
    {
        $curl = curl_init();
        $header =array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length:' . strlen(json_encode($data)),
            'Cache-Control: no-cache',
            'Pragma: no-cache'
        );
        if($headers){
            foreach($headers as $k=>$v){
                $header[] = $k.':'.$v;
            }
        }
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!$data) {
            return 'data is null';
        }
        if (is_array($data)) {
            $data = json_encode($data);
        }
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_TIMEOUT, 60); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        $errorno = curl_errno($curl);
        if ($errorno) {
            return $errorno;
        }
        curl_close($curl);
        return json_decode($res,true);
    }
}
